package com.sumainfor.wx.tenant.service.impl;

import com.sumainfor.common.EQBtsignConstants;
import com.sumainfor.common.config.LockUtil;
import com.sumainfor.common.entity.WxUserEntity;
import com.sumainfor.common.exception.TCException;
import com.sumainfor.common.util.*;
import com.sumainfor.common.utlis.ComUtils;
import com.sumainfor.common.utlis.ParamsCommon;
import com.sumainfor.wx.tenant.dao.IDinformationMapper;
import com.sumainfor.wx.tenant.dao.WechatMapper;
import com.sumainfor.wx.tenant.entity.TctenTenantBank;
import com.sumainfor.wx.tenant.entity.TctenTenantIdentit;
import com.sumainfor.wx.tenant.feign.DevelopmentFeignClient;
import com.sumainfor.wx.tenant.feign.MarketFeignClient;
import com.sumainfor.wx.tenant.service.IDinFormationService;
import com.sumainfor.wx.tenant.service.TctenTenantBankService;
import com.sumainfor.wx.tenant.service.TctenTenantIdentitService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 个人中心的证件信息
 *
 * @author xiaoma
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class IDinFormationServiceImpl implements IDinFormationService {

    private ReentrantLock lock = new ReentrantLock(false);

    @Autowired
    private LockUtil lockUtil;

    Logger log = LoggerFactory.getLogger(IDinFormationServiceImpl.class);
    @Autowired
    IDinformationMapper ifationbiz;

    @Autowired
    WechatMapper wxbiz;

    @Autowired
    DevelopmentFeignClient developmentFeignClient;

    @Autowired
    MarketFeignClient marketFeignClient;

    @Autowired
    private HttpUtil httpUtil;


    @Autowired
    private TctenTenantBankService bankService;

    @Autowired
    private TctenTenantIdentitService identitService;

    @Override
    public JsonResult getIDinfor(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        try {
            if (wxbiz.getCountusrinfor(params) > 0) {
                Map<String, Object> resmap = ifationbiz.getIDinfor(params);
                String idno = resmap.get("IDNumber").toString();//证件号码加密
                idno = idno.substring(0, 4);
                idno += "********";
                idno += idno.substring(idno.length() - 4, idno.length());
                resmap.put("IDNumber", idno);
                result.put(resmap);//查询到返回个人证件信息
            } else {
                result.putFailed("暂未查到您的证件信息,请先认证个人信息!");
            }
        } catch (Exception e) {

            result.putFailed("服务器繁忙...");
        }
        return result;
    }


    /**
     * 验证二要素
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult checkAccountTo2(Map<String, Object> params) {
        if (!FieldCheckUtil.isMapFieldNotNull(params, "name", "idno")) {
            return JsonResult.errorForEmpty();
        }

        JsonResult<Map<String, Object>> result = httpUtil.doPost(EQBtsignConstants.URL_OPENREALNAME + "/infoauth/psn/identity",
                CustomMap.create("name", params.get("name"))
                        .put("idno", params.get("idno")));
        if (result.isSuccess() == false) {
            return result;
        }
        Map<String, Object> dataResult = result.getResult();
        boolean pass = MapUtils.getBooleanValue(dataResult, "pass");
        if (!pass) {
            return JsonResult.error("实名认证校验不通过,请检查输入的信息是否是您本人信息");
        }
        return JsonResult.actionSuccess();
    }


    /**
     * 验证三要素
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult checkAccountTo3(Map<String, Object> params) {
        if (!FieldCheckUtil.isMapFieldNotNull(params, "name", "idno","cardno")) {
            return JsonResult.errorForEmpty();
        }

        JsonResult<Map<String, Object>> result = httpUtil.doPost(EQBtsignConstants.URL_OPENREALNAME + "/infoauth/psn/bankthree",
                CustomMap.create("name", params.get("name"))
                        .put("idno", params.get("idno"))
                        .put("cardno", params.get("cardno"))
        );
        if (result.isSuccess() == false) {
            return result;
        }
        Map<String, Object> dataResult = result.getResult();
        boolean pass = MapUtils.getBooleanValue(dataResult, "pass");
        if (!pass) {
            return JsonResult.error("实名认证校验不通过,请检查输入的信息是否是您本人信息");
        }
        return JsonResult.actionSuccess();
    }

    /**
     * 验证二要素要素，并更新用户信息
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult checkAccountElement(Map<String, Object> params) {

        WxUserEntity wxInfo = ContextUtils.getWxInfo();
//        JsonResult<Map<String, Object>> result = httpUtil.doPost(EQBtsignConstants.URL_OPENREALNAME + "/infoauth/psn/identity",
//                CustomMap.create("name", params.get("name"))
//                        .put("idno", params.get("idno"))
////                        .put("mobile", params.get("mobile"))
////                        .put("cardno", params.get("cardno"))
//        );
//        if (result.isSuccess() == false) {
//            return result;
//        }
//        Map<String, Object> dataResult = result.getResult();
//        boolean pass = MapUtils.getBooleanValue(dataResult, "pass");
//        if (!pass) {
//            return JsonResult.error("实名认证校验不通过,请检查输入的信息是否是您本人信息");
//        }
        //通过的情况
        TctenTenantIdentit card = new TctenTenantIdentit();
        card.setIdcode(UUIDUtils.generatePrefixUuid("ID_"));
        card.setTenId(wxInfo.getTenId());
        card.setCertiftype(1);
        card.setRealname(MapUtils.getString(params, "name"));
        card.setIDNumber(MapUtils.getString(params, "idno"));
        card.setFrontphoto(MapUtils.getString(params, "Frontphoto"));
        card.setFrontpside(MapUtils.getString(params, "Frontpside"));
        card.setInstm(LocalDateTime.now());
        boolean save = identitService.save(card);
        if (save == false) {
            return JsonResult.error("保存失败:01");
        }
        TctenTenantBank bank = new TctenTenantBank();
        bank.setBcode(UUIDUtils.generatePrefixUuid("BCO_"));
        bank.setTenId(wxInfo.getTenId());
        bank.setPayeename(MapUtils.getString(params, "name"));
       // bank.setBelongsbank(MapUtils.getString(params, "Belongsbank"));
       // bank.setBanknumber(MapUtils.getString(params, "cardno"));
        bank.setInstm(LocalDateTime.now());
        save = bankService.save(bank);
        if (save == false) {
            throw new TCException("保存失败:02");
        }
        return JsonResult.actionSuccess();
    }


    /**
     * 绑定身份信息
     *
     * @param params
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult savaidentit(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            params.put("term", "1");// 创建端 Insert端： 1 用户端 2 PC端 3 待定
            params.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(params);
            params.put("Idcode", ComUtils.randomUID("Id"));//生成uuid;
            if (ifationbiz.savaidentit(params) > 0) {
                result.putSuccess("操作成功");
            } else {
                result.putFailed("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult savework(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            if (ifationbiz.getcountwork(params) > 0) {
                log.info("修改操作");
                params.put("term", "1");// 创建端 Insert端： 1 用户端 2 PC端 3 待定
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                if (ifationbiz.updatework(params) > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("操作失败");
                }
            } else {
                log.info("新增操作");
                params.put("term", "1");// 创建端 Insert端： 1 用户端 2 PC端 3 待定
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                params.put("Wcode", ComUtils.randomUID("wco"));//生成uuid;
                if (ifationbiz.savework(params) > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("操作失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    @Override
    public JsonResult getindirection() {
        JsonResult result = new JsonResult();
        result.put(ifationbiz.getindirection());
        return result;
    }

    @Override
    public JsonResult getwode(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (ifationbiz.getcountwork(params) > 0) {
            result.put(ifationbiz.getwork(params));
        } else {
            result.putFailed("暂未查到您的工作信息");

        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult saveschool(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {

            if (ifationbiz.getcountschool(params) > 0) {
                log.info("修改操作");
                params.put("term", "1");// 创建端 Insert端： 1 用户端 2 PC端 3 待定
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                if (ifationbiz.updateschool(params) > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("操作失败");
                }
            } else {
                log.info("新增操作");
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                params.put("Schcode", ComUtils.randomUID("Sch"));//生成uuid;
                if (ifationbiz.saveschool(params) > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("操作失败");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    @Override
    public JsonResult getschool(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (ifationbiz.getcountschool(params) > 0) {
            result.put(ifationbiz.getschool(params));
        } else {
            result.putFailed("暂未查到您的学历信息");
        }
        return result;
    }

    @Override
    public JsonResult getbankByid(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        if (ifationbiz.getcountbank(params) > 0) {
            Map<String, Object> resmap = ifationbiz.getbankByid(params);
            String idno = resmap.get("Banknumber").toString();//证件号码加密
            idno = idno.substring(0, 4);
            idno += "**************";
            idno += idno.substring(idno.length() - 4, idno.length());
            resmap.put("IDNumber", idno);
            result.put(resmap);//查询到返回个人证件信息
        } else {
            result.putFailed("暂未查到您的银行卡信息");
        }
        return result;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult savebank(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {

            if (ifationbiz.getcountbank(params) > 0) {
                log.info("修改操作");
                params.put("term", "1");// 创建端 Insert端： 1 用户端 2 PC端 3 待定
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                if (ifationbiz.updatebank(params) > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("操作失败");
                }
            } else {
                log.info("新增操作");
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                params.put("Bcode", ComUtils.randomUID("Bco"));//生成uuid;
                if (ifationbiz.savebank(params) > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("操作失败");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    @Override
    public JsonResult gettenantTenSerpad(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        String datamap = ifationbiz.gettenantTenSerpad(params);

        if (datamap == null) {


            result.putFailed("您暂未设置服务密码");

        } else {

            result.putSuccess("服务密码已设置");
        }

        return result;
    }

    @Override
    public JsonResult getusrTenPhonebyid(Map<String, Object> params) {
        JsonResult result = new JsonResult();

        result.put(ifationbiz.getusrTenPhonebyid(params));

        return result;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult updateTenSerpadById(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {

            if (ifationbiz.updateTenSerpadById(params) > 0) {

                result.putSuccess("操作成功");
            } else {
                result.putFailed("操作成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    @Override
    public JsonResult getencrypted(Map<String, Object> params) {
        JsonResult result = new JsonResult();

        if (ifationbiz.getencrypted(params) > 0) {

            result.putSuccess("您已设置密保问题");
        } else {
            result.putFailed("您暂未设置密保问题");
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult saveencrypted(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            if (ifationbiz.getencrypted(params) > 0) {
                log.info("修改操作");
                params.put("term", "1");// 创建端 Insert端： 1 用户端 2 PC端 3 待定
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonUpdateParms(params);
                if (ifationbiz.updateencrypted(params) > 0) {
                    result.putSuccess("操作成功");

                } else {
                    result.putFailed("操作失败");
                }
            } else {
                log.info("新增操作");
                params.put("fnc",
                        this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
                ParamsCommon.commonInsertParms(params);
                params.put("Encode", ComUtils.randomUID("Enc"));//生成uuid;
                if (ifationbiz.saveencrypted(params) > 0) {
                    result.putSuccess("操作成功");
                } else {
                    result.putFailed("操作失败");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult savesuggest(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            params.put("fnc",
                    this.getClass().getSimpleName() + "." + Thread.currentThread().getStackTrace()[1].getMethodName());// 创建Function名
            ParamsCommon.commonInsertParms(params);
            params.put("Sugcode", ComUtils.randomUID("Sug"));//生成uuid;

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            params.put("Submittime", df.format(new Date()));//获取提交时间
            log.info("params====================>" + params);

            if (ifationbiz.savesuggest(params) > 0) {
                result.putSuccess("感谢您的建议,唐巣将会不断改进！");

            } else {
                result.putFailed("感谢您的建议,唐巣将会不断改进！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }


    /**
     * 查寻系统消息列表
     *
     * @param params
     * @return
     */
    @Override
    public JsonResult getSysmsgById(Map<String, Object> params) {
        JsonResult result = new JsonResult();


        //注册完才能看到创建的系统消息（注册时间》创建时间）
        List<Map<String, Object>> sysmap = ifationbiz.getSysmsgById(params);//首先获取list集合
        if (sysmap.size() != 0) {
            return developmentFeignClient.getMessageById(sysmap);
        } else {
            result.put(new ArrayList<Map<String, Object>>());
        }
        return result;

    }

    @Override
    public JsonResult getSysmsgInfoById(Map<String, Object> params) {
        ifationbiz.upateSysmsg(params);
        return developmentFeignClient.getMessageinfoById(params);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult deleteSysmsgById(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            if (ifationbiz.deleteSysmsgById(params) > 0) {
                result.putSuccess("操作成功");
            } else {
                result.putFailed("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }

    /***
     * 查询我的收藏
     * @param params
     * @return
     */
    @Override
    public JsonResult getTenantLikeById(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        List<Map<String, Object>> data = ifationbiz.getTenantLikeById(params);
        if (data.size() != 0) {
            return marketFeignClient.getHousingInfoState(data);
        } else {
            result.putFailed("您暂未添加喜爱的房源");
        }
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult deleteLikeById(Map<String, Object> params) {
        JsonResult result = new JsonResult();
        /**
         * 加锁操作
         */
        lock.lock();
        try {
            if (ifationbiz.deleteLikeById(params) > 0) {
                result.putSuccess("操作成功");
            } else {
                result.putFailed("操作失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//事物回滚
            result.putFailed("服务器繁忙...");
        } finally {
            lock.unlock();
        }
        return result;
    }


}
